<template>
  <div>
    <el-table :data="dataSource" border>
      <el-table-column type="expand">
        <template #default="{ row }">
          <el-row v-for="(item, index) in row.children" :key="item.id">
            <el-col :span="4"
              ><el-tag @close="handleClose(row, item.id)" closable>{{
                item.authName
              }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="20">
              <el-row v-for="two in item.children" :key="two.id">
                <el-col :span="4">
                  <el-tag
                    type="success"
                    @close="handleClose(row, two.id)"
                    closable
                    >{{ two.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="20">
                  <el-row v-for="three in two.children" :key="three.id">
                    <el-col>
                      <el-tag
                        type="danger"
                        @close="handleClose(row, three.id)"
                        closable
                      >
                        {{ three.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="序号"> </el-table-column>
      <el-table-column label="角色名称"> 
        <template #default="{row}">
          <div v-show="!row.flag">{{row.roleName}}</div>
          <el-input v-show="row.flag" type="text" v-model="row.roleName" size="small"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="角色描述"> 
        <template #default="{row}">
          <div v-show="!row.flag">{{row.roleDesc}}</div>
          <el-input v-show="row.flag" type="text" v-model="row.roleDesc" size="small"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="添加">
        <template slot="header">
          <el-button type="primary" @click="tianjiaVisible = true">添加角色</el-button>
        </template>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button @click="goEdite(row)" size="small" type="primary" icon="el-icon-edit"
              >{{row.flag?'完成':'修改'}}</el-button
            >
            <el-button @click="del(row.id)" size="small" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="small"
              type="warning"
              icon="el-icon-s-tools"
              @click="goSetRight(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <!-- 分配权限的弹窗 -->
    <el-dialog title="提示" :visible.sync="setRightDialog" width="50%">
      <!-- node-key 指定复选框绑定的属性 -->
      <el-tree
        :data="treeData"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :props="defaultProps"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialog = false">取 消</el-button>
        <el-button @click="resetChecked">清空</el-button>
        <el-button @click="setAll">全选</el-button>
        <el-button type="primary" @click="setRight">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色的弹窗 -->
    <el-dialog title="添加角色" :visible.sync="tianjiaVisible" width="30%">
      <el-form
        label-width="80px"
        size="small"
        style="width: 270px"
        :model="abcObj"
        ref="ruleForm"
      >
        <el-form-item label="角色名称:">
          <el-input type="text" v-model="abcObj.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:">
          <el-input type="text" v-model="abcObj.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="tianjiaVisible = false">取 消</el-button>
        <el-button type="primary" @click="doupdate()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  api_role_query,
  api_serRight,
  api_dalteRight,
  api_rolestj,
  api_deleting,
  api_update
} from "../../api/role.js";
import { api_getRight } from "../../api/right.js";
export default {
  data() {
    return {
      //表格数据源
      dataSource: [],
      //分配权限弹窗
      setRightDialog: false,
      //树形组件的数据源
      treeData: [],
      //指定树形控件中显示的标题的属性和子菜单的属性
      defaultProps: {
        children: "children",
        label: "authName",
      },
      //获取所有最后一级权限id的数组
      rightIds: [],
      //分配角色的id
      roleId: 0,
      //记录全选的数组
      allId: [],
      //添加角色的数据源
      abcObj: {
        roleName: "",
        roleDesc:""
      },
       //添加用户弹窗
      tianjiaVisible: false,
    };
  },
  mounted() {
    this.query();
  },
  methods: {
    //编辑
    async goEdite(row){
      if(row.flag){
      let rst= await api_update({id:row.id,roleName:row.roleName,roleDesc:row.roleDesc})
      console.log(rst);
      let {status}=rst.meta
      if(status==200){
        let { roleName } = rst.data;
        this.$message.success(`用户:${roleName}"修改成功"`);
      }
      }
       row.flag = !row.flag;

    },
    //删除
    async del(id){
       let rst= await api_deleting({id});
       let {status,msg}=rst.meta;
       if(status==200){
        this.$message.success(msg);
        this.query();
       }
    },
    //添加
    doupdate() {
      this.$refs.ruleForm.validate(async (b)=>{
        if(b){
          let rst= await api_rolestj(this.abcObj);
          console.log(rst);
          let {status,msg}=rst.meta;
          if(status==201){
            this.tianjiaVisible=false;
            this.$message.success(msg);
            this.query();
            this.abcObj={};
          }
        }
      })
        
        
    },
    //查询
    async query() {
      let rst = await api_role_query();
      console.log(rst);
      let { data } = rst;
      this.dataSource = data;
      data.forEach((item)=>{
        this.$set(item,'flag',false);
      })
      
    },
    async goSetRight(row) {
      this.rightIds = [];
      this.setRightDialog = true;
      // 为当前角色id赋值
      this.roleId = row.id;
      //获取所有tree的数据
      let rst = await api_getRight({ url: "tree" });
      this.treeData = rst.data;

      this.setRightId(row, this.rightIds);

      //获取所有的三极权限的id数组
      const treeAllObj = {
        children: [],
      };
      treeAllObj.children = rst.data;
      this.setRightId(treeAllObj, this.allId);
      //数据回填,在回填之前要获取当前角色所有的权限且是最后一级的权限id值
      this.$refs.tree.setCheckedKeys(this.rightIds);
    },
    //递归函数，在函数中调用自己本身，用于将所有的最后一级的权限id添加到数组中
    setRightId(obj, arr) {
      if (!obj.children) {
        arr.push(obj.id);
        return;
      }
      obj.children.forEach((item) => {
        this.setRightId(item, arr);
      });
    },
    //点击确定按钮触发的函数
    async setRight() {
      //获取 roleId 和rids（所有选中的树形组件的id拼接为一个数组然后转为string字符串以逗号分隔）
      let halfkeys = this.$refs.tree.getHalfCheckedKeys();
      let currentkeys = this.$refs.tree.getCheckedKeys();
      //合并数组逗号分隔
      let rids = [...halfkeys, ...currentkeys].join(",");
      let rst = await api_serRight({ roleId: this.roleId, rids });
      let { msg, status } = rst.meta;
      console.log(rst);
      if (status == 200) {
        this.$message.success(msg);
        this.setRightDialog = false;
        this.query();
      }
    },
    //点击移出角色菜单的方法
    async handleClose(row, rightId) {
      let rst = await api_dalteRight({ roleId: row.id, rightId });
      let { status, msg } = rst.meta;
      if (status == 200) {
        row.children = rst.data;
        this.$message.success(msg);
      }
    },
    //清空复选框的函数
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },
    //全选
    setAll() {
      this.$refs.tree.setCheckedKeys(this.allId);
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
</style>